package com.inhim.pjhim.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.URLUtil;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.dowloadfile.download.DownloadInfo;
import com.inhim.pjhim.dowloadfile.download.MyBusinessInfoDid;
import com.inhim.pjhim.dowloadfile.download.limit.DownloadLimitManager;
import com.inhim.pjhim.dowloadfile.ui.ListActivity;
import com.inhim.pjhim.entity.DownloadAuthor;
import com.inhim.pjhim.entity.IsValid;
import com.inhim.pjhim.entity.ProjectListEntity;
import com.inhim.pjhim.entity.ReaderInfo;
import com.inhim.pjhim.fragment.JIangyiFragment;
import com.inhim.pjhim.fragment.MuluFragment;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.ImageLoaderUtils;
import com.inhim.pjhim.utils.PrefUtils;
import com.inhim.pjhim.utils.ScreenUtils;
import com.inhim.pjhim.utils.StatusBarUtils;
import com.inhim.pjhim.utils.WXShareUtils;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.JudgeNestedScrollView;
import com.inhim.pjhim.view.VideoFloatView;
import com.inhim.pjhim.view.WrapContentHeightViewPager;
import com.pili.pldroid.player.AVOptions;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCMediaManager;
import fm.jiecao.jcvideoplayer_lib.JCRadioPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Request;

//单个章节
@SuppressLint("SetJavaScriptEnabled")
public class VideoActivity extends BaseActivity implements
        JCVideoPlayerStandard.DowloadVedioListener, MuluFragment.OnVideoLinear, JCVideoPlayer.CheckVedioListener {

    ImageView iv_back;
    private TextView iv_share;
    String name;
    public static String contents;
    private String photoUrl;

    JCVideoPlayerStandard mJcVideoPlayerStandard;
    private boolean mIsLiveStreaming = false;
    private WrapContentHeightViewPager viewPager;
    private ArrayList<Fragment> fs;
    Long id;
    String videoUrl, videoPath;
    File videoFile;
    private String results;
    private String vedioName;
    private ReaderInfo.Reader readerInfo;
    private CheckBox checkbox;
    private Gson gson;
    //下载得视频 课程
    private MyBusinessInfoDid businessInfoDid;
    private String title;
    private String description;
    private String TAG;
    private OrientationEventListener mOrientationListener;
    private boolean isFullScreen;
    private TextView textview1, textview2, textview4, textview6;
    private RadioButton iv_download;
    private TextView tv_name;
    private JudgeNestedScrollView scrollView;
    int toolBarPositionY = 0;
    int videoPositionY = 0;
    private RelativeLayout re_title;
    MagicIndicator magicIndicator;
    private String[] mTitles = new String[]{"讲义", "目录"};
    private List<String> mDataList = Arrays.asList(mTitles);
    MagicIndicator magicIndicatorTitle;
    private int mOffset = 0;
    private int mScrollY = 0;
    private ConstraintLayout con_video;
    private DownloadAuthor mDownloadAuthor;
    private ConstraintLayout con_caozuo;
    private long time;
    private boolean mIsPlaying;
    private int mDuration;
    @Override
    public Object offerLayout() {
        return R.layout.activity_video;
    }

    @Override
    public void onBindView() {
        Log.d("zhiqiang","isPlayingKey:"+PrefUtils.getBoolean(isPlayingKey,false));
        if(!PrefUtils.getBoolean(isPlayingKey,false)){
            JCRadioPlayer.releaseAllVideos();
        }
        hideFloatingWindow();
        hideFloat();
        gson = new Gson();
        time = System.currentTimeMillis();
        instance = this;
        TAG = getIntent().getStringExtra("TAG");
        initView();
        mIsPlaying=getIntent().getBooleanExtra("isPlaying",true);
        mDuration=getIntent().getIntExtra("Duration",0);
        businessInfoDid = (MyBusinessInfoDid) getIntent().getSerializableExtra("result");
        //判断 是已下载视频 且内存中视频未被删除
        if (businessInfoDid != null && (new File(businessInfoDid.getFilePath())).exists()) {
            magicIndicatorTitle.setVisibility(View.GONE);
            magicIndicator.setVisibility(View.GONE);
            List<DownloadAuthor> downloadAuthors = LitePal.where("readerId = ?", businessInfoDid.getReaderId()).find(DownloadAuthor.class);
            if (downloadAuthors.size() > 0) {
                mDownloadAuthor = downloadAuthors.get(0);
            }
            loadDownloadContent(businessInfoDid);
            getReaderList();
        } else {
            int intentReaderId = getIntent().getIntExtra("ReaderId", 0);
            getReaderInfo(intentReaderId, true, true);
        }
        mOrientationListener = new OrientationEventListener(this,
                SensorManager.SENSOR_DELAY_NORMAL) {

            @Override
            public void onOrientationChanged(int orientation) {
                if (JCVideoPlayerStandard.isFullScreen) {
                    if (orientation == 90) {
                        changeToFullScreen(false);
                    } else if (orientation == 270) {
                        changeToFullScreen(true);
                    }
                    Log.v(TAG, "Orientation changed to " + orientation);
                }
            }
        };

        if (mOrientationListener.canDetectOrientation()) {
            Log.v(TAG, "Can detect orientation");
            mOrientationListener.enable();
        } else {
            Log.v(TAG, "Cannot detect orientation");
            mOrientationListener.disable();
        }

    }

    @Override
    public void destory() {
        mOrientationListener.disable();
        if (videoUrl != null && videoPath != null && ("mp3".equals(videoPath.substring(videoPath.length() - 3)) ||
                "mp3".equals(videoUrl.substring(videoUrl.length() - 3)))) {
            PrefUtils.putBoolean(isPlayingKey,true);
            PrefUtils.putString(isPlayingUrl,videoUrl);
        } else {
            PrefUtils.putBoolean(isPlayingKey,false);
            PrefUtils.putString(isPlayingUrl,"");
            JCVideoPlayer.releaseAllVideos();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("zhiqiang","onStop");
    }


    private final String isPlayingKey="playingRadio";
    private final String isPlayingUrl="playingUrl";

    @Override
    protected void onStart() {
        super.onStart();
        hideActionBar();
        if (mJcVideoPlayerStandard != null) {
            mJcVideoPlayerStandard.setListener((JCVideoPlayerStandard.DowloadVedioListener) this);
        }
    }

    private void getReaderInfo(int readerId, final boolean isOne, boolean isPlay) {
        showLoading("加载中");
        Log.d("zhiqiang", "time1:" + (System.currentTimeMillis() - time));
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncGet(Urls.getReaderInfo(readerId, PrefUtils.getString("token", "")), new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                Log.d("zhiqiang", "time2:" + (System.currentTimeMillis() - time));
                ReaderInfo readerInfos = gson.fromJson(result, ReaderInfo.class);
                if (readerInfos.getCode() == 000) {
                    results = result;
                    mReaderId=readerId;
                    Log.d("zhiqiang", "time3:" + (System.currentTimeMillis() - time));
                    loadContent(readerInfos, isOne, isPlay);
                }
            }
        });
    }

    private int mReaderId;

    private void collectionReader(CheckBox mCheckBox, int readerId) {
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncJsonPost(Urls.collectionReader(readerId), new HashMap(),
                new MyOkHttpClient.HttpCallBack() {
                    @Override
                    public void onError(Request request, IOException e) {
                        if (mCheckBox.isChecked()) {
                            mCheckBox.setChecked(false);
                        } else {
                            mCheckBox.setChecked(true);
                        }
                    }

                    @Override
                    public void onSuccess(Request request, String result) {
                        hideLoading();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getInt("code") != 0) {
                                BToast.showText(jsonObject.getString("msg"), false);
                                //收藏失败时将按钮状态还原
                                if (mCheckBox.isChecked()) {
                                    mCheckBox.setChecked(false);
                                } else {
                                    mCheckBox.setChecked(true);
                                }
                            } else {
                                if (mCheckBox.isChecked()) {
                                    BToast.showText("收藏成功", true);
                                } else {
                                    BToast.showText("已取消收藏", true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void loadDownloadContent(MyBusinessInfoDid businessInfoDid) {
        if (businessInfoDid != null) {
            textview1.setText(businessInfoDid.getTitle());
            if (businessInfoDid.getReaderTypeText() != null) {
                if(businessInfoDid.getTagName()==null || "".equals(businessInfoDid.getTagName())){
                    textview2.setVisibility(View.GONE);
                }else{
                    textview2.setVisibility(View.VISIBLE);
                    textview2.setText("分类：" + businessInfoDid.getTagName());
                }
                tv_name.setText(businessInfoDid.getReaderTypeText());
            }
            if (null != mDownloadAuthor) {
                //textview6.setText("作者：" + mDownloadAuthor.getName());
            }
            textview4.setText(businessInfoDid.getTimeText());
            description = businessInfoDid.getSynopsis();
            textview4.setText(businessInfoDid.getTimeText());
            description = businessInfoDid.getSynopsis();
        }
        title = businessInfoDid.getTitle();
        description = businessInfoDid.getSynopsis();
        name = businessInfoDid.getTitle();
        contents = businessInfoDid.getContent();
        photoUrl = businessInfoDid.getCover();
        videoPath = businessInfoDid.getFilePath();
        videoUrl = businessInfoDid.getUrl();
        videoFile = new File(videoPath);
        checkbox.setChecked(Boolean.valueOf(businessInfoDid.getCollectionStatus()));
        if (videoFile.exists()) {
            iv_download.setChecked(true);
        }
        setVideo(false);
        Bundle jiangyiBl = new Bundle();
        jiangyiBl.putSerializable("businessInfoDid", businessInfoDid);
        jiangyiBl.putSerializable("DownloadAuthor", mDownloadAuthor);
        jiangyiBl.putString("content", contents);
        Bundle muluBl = new Bundle();
        muluBl.putInt("ReaderTypeId", businessInfoDid.getReaderTypeId());
        muluBl.putInt("ReaderId", Integer.valueOf(businessInfoDid.getReaderId()));
        fs = new ArrayList<>();
        JIangyiFragment jiangyiFm = new JIangyiFragment();
        //MuluFragment muluFragment = new MuluFragment();
        //监听目录列表点击切换视频 和文章内容
        //muluFragment.setvedioLinear(VideoActivity.this);
        jiangyiFm.setArguments(jiangyiBl);
        //muluFragment.setArguments(muluBl);
        fs.add(jiangyiFm);
        //fs.add(muluFragment);
        FragmentManager fm = getSupportFragmentManager();
        MyPagerAdapter adapter = new MyPagerAdapter(fm);
        viewPager.setAdapter(adapter);
    }

    JIangyiFragment jiangyiFm;
    MuluFragment muluFragment;

    private void loadContent(ReaderInfo readerInfos, boolean isOne, boolean isPlay) {
        readerInfo = readerInfos.getReader();
        if (readerInfo.getReaderTypeText() != null) {
            tv_name.setText(readerInfo.getReaderTypeText());
        } else {
            tv_name.setText("");
        }
        if (readerInfo != null) {
            textview1.setText(readerInfo.getTitle());
            if(readerInfo.getTagName()==null || "".equals(readerInfo.getTagName())){
                textview2.setVisibility(View.GONE);
            }/*else{
                if(businessInfoDid==null){
                    return;
                }
                if( businessInfoDid.getTagName()!=null){
                    textview2.setVisibility(View.VISIBLE);
                    textview2.setText("分类：" + businessInfoDid.getTagName());
                }
            }*/
            if (null != readerInfo.getAuthor()) {
                //textview6.setText("作者：" + readerInfo.getAuthor().getName());
            }
            //textview4.setText("上传时间：" + readerInfo.getCreateTime());
            description = readerInfo.getSynopsis();
        }
        title = readerInfo.getTitle();
        description = readerInfo.getSynopsis();
        checkbox.setChecked(readerInfo.getCollectionStatus());
        name = readerInfo.getTitle();
        if (readerInfo.getUrl() != null) {
            videoUrl = readerInfo.getUrl();
            vedioName = readerInfo.getUrl().substring(readerInfo.getUrl().lastIndexOf("/"));
        }
        contents = readerInfo.getContent();
        photoUrl = readerInfo.getCover();
        videoPath = Urls.getFilePath() + vedioName;
        videoFile = new File(videoPath);
        if (videoFile.exists()) {
            iv_download.setChecked(true);
        }
        if(isOne){
            Bundle jiangyiBl = new Bundle();
            jiangyiBl.putSerializable("result", readerInfo);
            jiangyiBl.putString("content", contents);
            fs = new ArrayList<>();
            jiangyiFm = new JIangyiFragment();
            jiangyiFm.setArguments(jiangyiBl);
            fs.add(jiangyiFm);
            FragmentManager fm = getSupportFragmentManager();
            MyPagerAdapter adapter = new MyPagerAdapter(fm);
            viewPager.setAdapter(adapter);
        }
        Log.d("zhiqiang", "time4:" + (System.currentTimeMillis() - time));
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (isOne) {
                    Bundle muluBl = new Bundle();
                    muluBl.putInt("ReaderTypeId", readerInfo.getReaderTypeId());
                    muluBl.putInt("ReaderId", readerInfo.getReaderId());
                    //只有从首页的视频页面进入视频才显示目录
                    //if ("VideoFragment".equals(TAG)) {
                    muluFragment = new MuluFragment();
                    muluFragment.setvedioLinear(VideoActivity.this);
                    muluFragment.setArguments(muluBl);
                    fs.add(muluFragment);
                    //}
           /* if(!readerInfo.getReaderStyleIdLink().contains("#3")){

            }*/
                    FragmentManager fm = getSupportFragmentManager();
                    MyPagerAdapter adapter = new MyPagerAdapter(fm);
                    viewPager.setAdapter(adapter);
                    Log.d("zhiqiang", "time5:" + (System.currentTimeMillis() - time));
                } else {
            /*JCVideoPlayer.releaseAllVideos();
            Intent intent1 = new Intent();
            intent1.setAction("refresh.fragment.content");
            intent1.putExtra("content", contents);
            intent1.putExtra("result", readerInfo);
            sendBroadcast(intent1);*/
                    if (jiangyiFm != null) {
                        jiangyiFm.setContext(contents, readerInfo);
                    }
                }
                setVideo(isPlay);
                if (isOne) {
                    getReaderList();
                }
            }
        });
    }

    private Handler mMainHandler = new Handler();

    private void isValid(String urlString) {
        MyOkHttpClient myOkHttpClient = MyOkHttpClient.getInstance();
        myOkHttpClient.asyncGet(urlString, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                BToast.showText("网络错误", false);
            }

            @Override
            public void onSuccess(Request request, String result) {
                try {
                    IsValid isValid = gson.fromJson(result, IsValid.class);
                    if (isValid != null && isValid.getCode().equals("NoSuchKey")) {
                        if (videoFile != null && videoFile.exists()) {
                            videoPath = videoPath.replaceAll(".mp3", ".mp4");
                        } else {
                            mIsplayRadio = false;
                            videoUrl = videoUrl.replaceAll(".mp3", ".mp4");
                        }
                        BToast.showText("无音频文件");
                        return;
                    }else{
                        mIsplayRadio=true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mJcVideoPlayerStandard.setUp(videoUrl
                        , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
                mJcVideoPlayerStandard.playRadio();
            }
        });
    }

    private List<String> mRadioUrls = new ArrayList<>();
    private List<String> mVvideoUrls = new ArrayList<>();

    private void getReaderList() {
        int readerTypeId;
        if (businessInfoDid != null) {
            readerTypeId = businessInfoDid.getReaderTypeId();
        } else if (readerInfo != null) {
            readerTypeId = readerInfo.getReaderTypeId();
        } else {
            return;
        }
        HashMap postMap = new HashMap();
        postMap.put("readerTypeId", String.valueOf(readerTypeId));
        String url = Urls.getReaderList(1, 50, "asc");
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                ProjectListEntity readerLists = gson.fromJson(result, ProjectListEntity.class);
                projectListEntitys = readerLists.getPage().getList();
                for (int i = 0; i < readerLists.getPage().getList().size(); i++) {
                    if(readerLists.getPage().getList().get(i).getUrl()==null){
                        break;
                    }
                    mRadioUrls.add(readerLists.getPage().getList().get(i).getUrl().replaceAll(".mp4", ".mp3"));
                    mVvideoUrls.add(readerLists.getPage().getList().get(i).getUrl());
                    if(videoUrl==null){
                        return;
                    }
                    if (videoUrl.equals(readerLists.getPage().getList().get(i).getUrl())) {
                        mPlayPosition = i;
                    }
                }
            }
        });
    }

    private List<ProjectListEntity.List> projectListEntitys;
    private int mPlayPosition;
    private boolean mIsplayRadio;

    @Override
    public void checkRadio() {
        if (videoFile != null && videoFile.exists()) {
            if (videoPath.contains(".mp4")) {
                videoPath = videoPath.replaceAll(".mp4", ".mp3");
                videoUrl = videoUrl.replaceAll(".mp4", ".mp3");
                mIsplayRadio = true;
                //mJcVideoPlayerStandard.setUp(videoUrl, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
                isValid(videoUrl);
            } else {
                mIsplayRadio = false;
                videoPath = videoPath.replaceAll(".mp3", ".mp4");
                mJcVideoPlayerStandard.setUp(videoPath
                        , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
                if(mIsPlaying){
                    Log.d("zhiqiang","mDuration11:"+mDuration);
                    JCMediaManager.instance().mediaPlayer.seekTo(mDuration);
                    mJcVideoPlayerStandard.playRadio();
                }
            }

        } else {
            if (videoUrl.contains(".mp4")) {
                mIsplayRadio = true;
                videoUrl = videoUrl.replaceAll(".mp4", ".mp3");
                isValid(videoUrl);
            } else {
                mIsplayRadio = false;
                videoUrl = videoUrl.replaceAll(".mp3", ".mp4");
                mJcVideoPlayerStandard.setUp(videoUrl
                        , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
                if(mIsPlaying){
                    Log.d("zhiqiang","mDuration222:"+mDuration);
                    try {
                        JCMediaManager.instance().mediaPlayer.seekTo(mDuration);
                        mJcVideoPlayerStandard.playRadio();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    private void downloadVideo() {
        rxPermissionWriteAndRead(results);
    }

    private void rxPermissionWriteAndRead(String results) {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (VideoActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    VideoActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                    //查找当前url文件是否正在下载中
                    List<DownloadInfo> person = null;
                    if (businessInfoDid != null) {
                        person = LitePal.where("url = ?", businessInfoDid.getUrl()).find(DownloadInfo.class);
                    } else {
                        try {
                            person = LitePal.where("url = ?", readerInfo.getUrl()).find(DownloadInfo.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (videoFile != null && videoFile.exists()) {
                        BToast.showText("已下载");
                    } else if ((person != null && person.size() > 0)) {
                    /*Intent intent = new Intent(VideoActivity.this, ListActivity.class);
                        startActivity(intent);*/
                        //DownloadLimitManager.getInstance().download(readerInfo.getUrl());
                        BToast.showText("正在下载");
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject(results);
                            DownloadInfo businessInfo = gson.fromJson(jsonObject.getJSONObject("reader").toString(), DownloadInfo.class);
                            businessInfo.setFilePath(videoPath);
                            businessInfo.setProgress(0);
                            businessInfo.setProgressText("0");
                            businessInfo.setFileName(businessInfo.getUrl().substring(businessInfo.getUrl().lastIndexOf("/")));
                            businessInfo.setDownloadStatus("download");
                            boolean istrue = businessInfo.save();
                            DownloadAuthor saveAuthor = new DownloadAuthor();
                            saveAuthor.setReaderId(readerInfo.getReaderId());
                            if (readerInfo.getAuthor() != null) {
                                saveAuthor.setArea(readerInfo.getAuthor().getArea());
                                saveAuthor.setCreateTime(readerInfo.getAuthor().getCreateTime());
                                saveAuthor.setHeadPortrait(readerInfo.getAuthor().getHeadPortrait());
                                saveAuthor.setId(readerInfo.getAuthor().getId());
                                saveAuthor.setIdentity(readerInfo.getAuthor().getIdentity());
                                saveAuthor.setName(readerInfo.getAuthor().getName());
                                saveAuthor.setSynopsis(readerInfo.getAuthor().getSynopsis());
                            }
                            saveAuthor.save();
                            if (istrue) {
                            /*Intent intent = new Intent(VideoActivity.this, ListActivity.class);
                                startActivity(intent);*/
                                DownloadLimitManager.getInstance().download(businessInfo.getUrl());
                                DownloadLimitManager.getInstance().setTitle(businessInfo.getTitle());
                                BToast.showText("正在下载");
                            } else {
                                iv_download.setChecked(false);
                                BToast.showText("下载失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Override
    public void fullScreen() {
        changeToFullScreen(true);
    }

    @Override
    public void nextVideo() {
        if(mPlayPosition<projectListEntitys.size()-1){
            mPlayPosition += 1;
            setVidoUrl(projectListEntitys.get(mPlayPosition).getReaderId());
        }
    }

    @Override
    public void windowPlay(String urls) {
        if (!requestOverlayPermission()) {
            showFloatingWindow(VideoActivity.this,urls);
            finish();
        } else {
            BToast.showText( "请开启悬浮窗权限");
        }
    }

    @Override
    public void setVidoUrl(int ReaderId) {
        getReaderInfo(ReaderId, false, true);
    }

    private static final int REQUEST_OVERLAY_CODE = 1;
    private VideoFloatView mFloatingWindow;

    private void showFloatingWindow(Context context,String urls) {
        mFloatingWindow = new VideoFloatView();
        mFloatingWindow.initFloatView(urls, MyApplication.getContext(),JCMediaManager.instance().mediaPlayer.isPlaying(),getDuration(),mReaderId);
    }

    private void hideFloatingWindow(){
        VideoFloatView.dismiss();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_OVERLAY_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(VideoActivity.this)) {
                    showFloatingWindow(VideoActivity.this,videoUrl);
                } else {
                    BToast.showText( "获取悬浮窗权限失败");
                }
            }
        }
    }

    /**
     * 判断是否开启悬浮窗口权限，否则，跳转开启页
     */
    public boolean requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_OVERLAY_CODE);
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        //当前播放进度
        if (businessInfoDid != null) {
            int position = mJcVideoPlayerStandard.getCurrentPositionWhenPlaying();
            //获取当前播放进度
            int duration = getDuration();
            float num = (float) position / duration;
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数
            String progressTime = df.format(num);//返回的是String类型
            //格式化fat,保留两位小数, 得到一个string字符串
            if (progressTime != null && !progressTime.equals("NaN")) {
                DecimalFormat decimalFormat = new DecimalFormat(".00");
                String proess = decimalFormat.format(Float.valueOf(progressTime) * 100);
                MyBusinessInfoDid myBusinessInfoDid = new MyBusinessInfoDid();
                //第二步，改变某个字段的值
                myBusinessInfoDid.setProgressText("已观看" + proess + "%");
                //第三步，保存数据
                //更新所有readerId为readerId的记录,记录观看进度
                myBusinessInfoDid.updateAll("readerId = ?", businessInfoDid.getReaderId());
            }
        }
    }

    public int getDuration() {
        //视频总时间
        int duration = 0;
        if (JCMediaManager.instance().mediaPlayer == null) return duration;
        try {
            duration = JCMediaManager.instance().mediaPlayer.getCurrentPosition();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return duration;
        }
        return duration;
    }

    private void initView() {
        con_caozuo = findViewById(R.id.con_caozuo);
        con_video = findViewById(R.id.con_video);
        con_video.post(() -> videoPositionY = con_video.getHeight() + toolBarPositionY);
        magicIndicator = findViewById(R.id.magic_indicator);
        magicIndicatorTitle = findViewById(R.id.magic_indicator_title);
        re_title = findViewById(R.id.re_title);
        StatusBarUtils.immersive(this);
        //StatusBarUtils.setPaddingSmart(this, re_title);
        re_title.post(() -> dealWithViewPager());
        scrollView = findViewById(R.id.my_scrollview);
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            int lastScrollY = 0;
            int h = DensityUtil.dp2px(170);
            int color = ContextCompat.getColor(getApplicationContext(), R.color.white) & 0x00ffffff;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int[] location = new int[2];
                magicIndicator.getLocationOnScreen(location);
                int yPosition = location[1];
                if (businessInfoDid == null) {
                    if (yPosition < toolBarPositionY) {
                        magicIndicatorTitle.setVisibility(View.VISIBLE);
                        scrollView.setNeedScroll(true);
                    } else {
                        magicIndicatorTitle.setVisibility(View.GONE);
                        scrollView.setNeedScroll(true);

                    }
                }

                if (lastScrollY < h) {
                    scrollY = Math.min(h, scrollY);
                    mScrollY = scrollY > h ? h : scrollY;
                    //mJcVideoPlayerStandard.setTranslationY(mOffset - mScrollY);
                }
                lastScrollY = scrollY;
            }
        });
        iv_download = findViewById(R.id.iv_download);
        textview1 = findViewById(R.id.textview1);
        textview2 = findViewById(R.id.textview2);
        textview4 = findViewById(R.id.textview4);
        textview6 = findViewById(R.id.textview6);
        iv_share = findViewById(R.id.iv_share);
        tv_name = findViewById(R.id.tv_name);
        iv_share.setOnClickListener(v -> {
            if (businessInfoDid != null) {
                WXShareUtils.show(VideoActivity.this, Urls.shareH5(Integer.valueOf(businessInfoDid.getReaderId())), title, description);
            } else {
                WXShareUtils.show(VideoActivity.this, Urls.shareH5(readerInfo.getReaderId()), title, description);
            }
        });
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(v -> {
            try {
                if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                    if (System.currentTimeMillis() - previous > 4000) {
                        BToast.showText("再按一次退出");
                        previous = System.currentTimeMillis();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }

        });
        checkbox = findViewById(R.id.checkbox);
        viewPager = findViewById(R.id.viewpager);
        mJcVideoPlayerStandard = findViewById(R.id.jc_video);
        mJcVideoPlayerStandard.setListener((JCVideoPlayer.CheckVedioListener) VideoActivity.this);
        checkbox.setOnClickListener(v -> {
            collectionReader(checkbox, readerInfo.getReaderId());
        });
        iv_download.setOnClickListener(v -> downloadVideo());
        viewPager.setOffscreenPageLimit(10);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        con_caozuo.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        con_caozuo.setVisibility(View.GONE);
                        break;
                }

            }

            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            public void onPageScrollStateChanged(int arg0) {

            }
        });
        initMagicIndicator();
        initMagicIndicatorTitle();
    }

    private void initMagicIndicatorTitle() {
        /*CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setScrollPivotX(0.65f);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(VideoActivity.this, R.color.color_555));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(VideoActivity.this, R.color.baseColor));
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(index, false);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 2));
                indicator.setLineWidth(UIUtil.dip2px(context, 20));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(ContextCompat.getColor(VideoActivity.this, R.color.baseColor));
                return indicator;
            }
        });*/
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(VideoActivity.this);
                commonPagerTitleView.setContentView(R.layout.simple_pager_title_layout);

                // 初始化
                final ImageView titleImg = (ImageView) commonPagerTitleView.findViewById(R.id.title_img);
                final TextView titleText = (TextView) commonPagerTitleView.findViewById(R.id.title_text);
                titleText.setText(mDataList.get(index));

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        titleText.setTextColor(ContextCompat.getColor(VideoActivity.this, R.color.color333));
                        titleText.setTextSize(18);
                        titleText.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                        titleImg.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        titleText.setTextColor(ContextCompat.getColor(VideoActivity.this, R.color.color_555));
                        titleText.setTextSize(16);
                        titleText.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                        titleImg.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
                        titleImg.setScaleX(1.3f + (0.8f - 1.3f) * leavePercent);
                        titleImg.setScaleY(1.3f + (0.8f - 1.3f) * leavePercent);
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
                        titleImg.setScaleX(0.8f + (1.3f - 0.8f) * enterPercent);
                        titleImg.setScaleY(0.8f + (1.3f - 0.8f) * enterPercent);
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (index == 1) {
                            con_caozuo.setVisibility(View.GONE);
                        } else {
                            con_caozuo.setVisibility(View.VISIBLE);
                        }
                        viewPager.setCurrentItem(index, false);
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        magicIndicatorTitle.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicatorTitle, viewPager);

    }

    private void initMagicIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(VideoActivity.this);
                commonPagerTitleView.setContentView(R.layout.simple_pager_title_layout);

                // 初始化
                final ImageView titleImg = (ImageView) commonPagerTitleView.findViewById(R.id.title_img);
                final TextView titleText = (TextView) commonPagerTitleView.findViewById(R.id.title_text);
                titleText.setText(mDataList.get(index));

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        titleText.setTextColor(ContextCompat.getColor(VideoActivity.this, R.color.color333));
                        titleText.setTextSize(18);
                        titleText.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                        titleImg.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        titleText.setTextColor(ContextCompat.getColor(VideoActivity.this, R.color.color_555));
                        titleText.setTextSize(16);
                        titleText.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                        titleImg.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
                        titleImg.setScaleX(1.3f + (0.8f - 1.3f) * leavePercent);
                        titleImg.setScaleY(1.3f + (0.8f - 1.3f) * leavePercent);
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
                        titleImg.setScaleX(0.8f + (1.3f - 0.8f) * enterPercent);
                        titleImg.setScaleY(0.8f + (1.3f - 0.8f) * enterPercent);
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (index == 1) {
                            con_caozuo.setVisibility(View.GONE);
                        } else {
                            con_caozuo.setVisibility(View.VISIBLE);
                        }
                        viewPager.setCurrentItem(index, false);
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);
    }

    private void dealWithViewPager() {
        toolBarPositionY = re_title.getHeight();
        ViewGroup.LayoutParams params = viewPager.getLayoutParams();
        params.height = ScreenUtils.getScreenHeightPx(getApplicationContext()) - toolBarPositionY - magicIndicator.getHeight() + 1;
        viewPager.setLayoutParams(params);
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }


    private void setVideo(boolean isPlay) {
        Log.d("zhiqiang", "time6:" + (System.currentTimeMillis() - time));
        if(PrefUtils.getBoolean(isPlayingKey,false)){
            String lastUrl=PrefUtils.getString(isPlayingUrl,"");
            lastUrl = lastUrl.replace(".mp3","");
            String presentUrl=videoUrl.replace(".mp4","");
            if(presentUrl.equals(lastUrl)){
                videoUrl=PrefUtils.getString(isPlayingUrl,"");
            }else{
                JCVideoPlayer.releaseAllVideos();
            }
        }else{
            JCVideoPlayer.releaseAllVideos();
        }
        if (videoFile != null && videoFile.exists()) {
            mJcVideoPlayerStandard.setUp(videoPath
                    , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
        } else {
            if(videoUrl!=null&& name!=null){
                mJcVideoPlayerStandard.setUp(videoUrl
                        , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, name);
            }
        }

        /*Picasso.with(this)
                .load(photoUrl)
                .into(mJcVideoPlayerStandard.thumbImageView);*/
        //ImageLoaderUtils.setImage(photoUrl, mJcVideoPlayerStandard.thumbImageView);
        //屏幕保持常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // 1 -> hw codec enable, 0 -> disable [recommended]
        int codec = getIntent().getIntExtra("mediaCodec", AVOptions.MEDIA_CODEC_SW_DECODE);
        AVOptions options = new AVOptions();
        // the unit of timeout is ms
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, codec);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, mIsLiveStreaming ? 1 : 0);
        boolean disableLog = getIntent().getBooleanExtra("disable-log", false);
        options.setInteger(AVOptions.KEY_LOG_LEVEL, disableLog ? 5 : 0);
        boolean cache = getIntent().getBooleanExtra("cache", false);
        if (!mIsLiveStreaming && cache) {
            options.setString(AVOptions.KEY_CACHE_DIR, Urls.getFilePath());
        }
        boolean vcallback = getIntent().getBooleanExtra("video-data-callback", false);
        if (vcallback) {
            options.setInteger(AVOptions.KEY_VIDEO_DATA_CALLBACK, 1);
        }
        if (isPlay) {
            mJcVideoPlayerStandard.playRadio();
        }
    }


    private VideoActivity instance;

    /**
     * 横屏
     * isLeft参数代表是向左横屏还是向右横屏
     *
     * @param
     */
    // 按返回键退出
    long previous = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && (mJcVideoPlayerStandard.isFullScreen == true)) {
            //fullScreenToNormal();
            mJcVideoPlayerStandard.backPress();
            return false;
        } else if (keyCode == 4) {
            try {
                if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                    if (System.currentTimeMillis() - previous > 4000) {
                        BToast.showText("再按一次退出");
                        previous = System.currentTimeMillis();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
                finish();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    // 竖屏
    @SuppressLint("SourceLockedOrientationActivity")
    private void fullScreenToNormal() {
        isFullScreen = false;
        instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    @SuppressLint("SourceLockedOrientationActivity")
    private void changeToFullScreen(boolean isLeft) {
        mJcVideoPlayerStandard.isFullScreen = true;
        isFullScreen = true;
        if (isLeft) {
            // 向左横屏
            instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            // 向右横屏
            instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        }
    }

    /**
     * 自定义适配器  FragmentPagerAdapter
     */
    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fs.get(arg0);
        }

        @Override
        public int getCount() {
            return fs.size();
        }
    }

}
